package com.mach.platform.repository;

import com.mach.platform.domain.base.Permission;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Anonymous
 * @Description:  权限数据接口
 * @Package: com.mach.platform.com.mach.platform.repository
 * @time 2018/04/03 22:53
 */
@Repository
public interface PermissionRepo extends BaseRepository<Permission> {

	/**
	 * 查询当前角色 所拥有的权限，返回权限列表
	 * @param roleId 角色id
	 * @return Page<Permission>
	 */
	@Query(value = "select * from permission where id in (select distinct perm_id from role_perm where role_id=?1)",nativeQuery = true)
	List<Permission> loadPermissionsInRoleRelation (Long roleId);

	/**
	 * 主要是 登录时候，存进合法登录信息的时候用
	 * 根据用户名 查询 该用户所对应角色 留，所拥有的全部权限
	 * @param username 用户名
	 * @return List<Permission>
	 */
	@Query(value = "select * from permission p where p.id in (select distinct rp.perm_id from role r join role_perm rp on rp.role_id = r.id join role_account ar on ar.role_id = r.id join account a on a.id = ar.account_id where a.username = ?1)",nativeQuery = true)
	List<Permission> loadPermissionsByUserName (String username);

	/**
	 * 删除权限的时候，同时删除权限-角色关系表的数据
	 *
	 * @param permIds
	 * @return
	 */
	@Modifying
	@Query(value = "delete from role_perm where perm_id in ?1", nativeQuery = true)
	Integer deleteRelationWhileDeletePerms (Long[] permIds);

}
